package com.csproj.basic.repository.impl;

import com.csproj.basic.domain.Path;
import com.csproj.basic.repository.custom.PathRepositoryCustom;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PathRepositoryImpl implements PathRepositoryCustom {
    @PersistenceContext
    private EntityManager em;

    public EntityManager getEm() {
        return em;
    }

    /**
     * 机构分页查询方法
     * @param map	参数
     * @param pageable		分页对象
     * @return
     */
    public Page<Path> findPageList(Map<String, Object> map, Pageable pageable) {
        //拼hql
        String hql = " from Path p where p.deletedFlag = 0 ";
        Map<String,Object> queryParams = new HashMap<>();

        String pathNo = (String) map.get("pathNo");
        if (StringUtils.isNotBlank(pathNo)) {
            hql += " and p.pathNo like :pathNo";
            queryParams.put("pathNo","%"+pathNo+"%");
        }
        String siteId = (String) map.get("siteId");
        if (StringUtils.isNotBlank(siteId)&& !siteId.equals("nositeID")) {
            hql += " and (p.startSiteId = :siteId1 or p.endSiteId = :siteId2) ";
            queryParams.put("siteId1", siteId);
            queryParams.put("siteId2", siteId);
        }
        String startSiteId = (String) map.get("startSiteId");
        if (StringUtils.isNotBlank(startSiteId)) {
            hql += " and p.startSiteId = :startSiteId ";
            queryParams.put("startSiteId", startSiteId);
        }

        String endSiteId = (String) map.get("endSiteId");
        if (StringUtils.isNotBlank(endSiteId)) {
            hql += " and p.endSiteId = :endSiteId ";
            queryParams.put("endSiteId", endSiteId);
        }
        //查询
        Page<Path> fieldList = query(hql, pageable, queryParams);
        //返回
        return fieldList;
    }

    /**
     * 机构列表查询方法
     * @param map	参数
     * @return
     */
    public List<Path> findListBySiteId(Map<String, Object> map){
        //拼hql
        String hql = " from Path p where p.deletedFlag = 0 and enableFlag =1 ";
        Map<String,Object> queryParams = new HashMap<>();

        String startSiteId = (String) map.get("startSiteId");
        if (StringUtils.isNotBlank(startSiteId)) {
            hql += " and p.startSiteId like :startSiteId";
            queryParams.put("startSiteId",startSiteId);
        }

        List<Path> list = query(hql,queryParams);
        return  list;
    }
}
